<html>

<meta charset="utf-8">

<head>

<title>海洋牧场智慧可视化系统</title>
<!--<link href="../static/css/_style.css" rel="stylesheet" type="text/css" media="all" />-->
<!-- <link rel="stylesheet" type="text/css" href= "{{ url_for('static', filename = 'css/smartCenter.css') }}"> -->
<link rel="stylesheet" type="text/css" href= "../static/css/smartCenter.css?v=2012">

<!-- 禁用缓存 -->
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

</head>

<body>
    <div class="main">
        <div class="header">
            <div class="topbnt_left fl">
                <ul>
                    <li><a href="/mainInfo">主要信息</a></li>
                    <li><a href="/waterSystem">水下系统</a></li>
                </ul>
            </div>
            <h1 class="tith1 fl">海洋牧场智慧可视化系统</h1>
            <div class=" fr topbnt_right">
                <ul>
                    <li><a href="/dataCenter">数据中心</a></li>
                    <li><a href="/smartCenter">智能中心</a></li>
                </ul>
            </div>
            <a href="/admain" class="admain"></a>
        </div>


        <div class="content">
            <!-- 左边 -->
            <div class="content-left">
                <!-- 左边上面 -->
                <div class="content-title">
                    <span>环境综合评价</span>
                </div>
                <div class="left-top">
                    <div id="table0" class="_table0"></div>
                </div>

                <!-- 左边下面 -->
                <div class="left-bottom">
                    <span>近期环境</span>
                    <!-- <div id="test" style="width: 600px;height:400px;"></div> -->
                    <div id="table1" class="_table1"></div>
                </div>
            </div>

            <!-- 中间 -->
            <div class="content-center">
                <!-- 中间上面 -->
                <div class="center-top">
                    <span>实时监控</span>
                    <div class="center-pic"><img id="centerFig" src="../static/img/smartCenter/fish/caoyu.jpg" style="height: 100%;"></div>
                    <button id="switch" style="background-color: cornflowerblue;width: 30rem;height: 12rem;margin-right: 5rem;">switch</button>
                    <button id="upload" style="background-color: cornflowerblue;width: 30rem;height: 12rem;">upload</button>
                    <button id="update" style="background-color: cornflowerblue;width: 30rem;height: 12rem;margin-left: 5rem;">update</button>
                </div>


                <!-- 中间下面 -->
                <div class="content-title">
                    <span style="font-size: 18px;margin-left:70rem">实时数据</span>

                </div>
                <div class="center-bottom">
                    <!-- 下上 -->
                    <div class="bottom-top">
                        <div class="bottom-pic"><img id="myfish" src="../static/img/smartCenter/8.png" style="height: 100%;"></div>
                        <div class="bottom-middle"></div>
                        <div class="bottom-text">
                            <ul>
                                <li >编号：<span id="fishId">AS0092</span></li>
                                <li>种类：<span id="fishName">扇形海鱼</span></li>
                                <li>prob：<span id="prob">0.98</span></li>
                            </ul>
                        </div>
                    </div>

                    <!-- 下下 -->
                    <div class="bottom-bottom">
                        <div calss="bottom-left">
                            <table style="margin-top: 10rem;margin-left:5rem">
                                <tr>
                                    <th>Length1</th>
                                    <th>Length2</th>
                                    <th>Length3</th>
                                    <th>Height</th>
                                    <th>Width</th>
                                    <th class="clickable" onclick="handleClick()">Weight</th>
                                </tr>
                                <tr>
                                    <td id="Length1">2</td>
                                    <td id="Length2">2</td>
                                    <td id="Length3">222</td>
                                    <td id="Height">333</td>
                                    <td id="Width">111</td>
                                    <td id="Weight" style="color: red;">222</td>
                                </tr>
                            </table>
                        </div>
                        <div calss="bottom-right">

                        </div>
                        <!-- <div class="box">
                            <p>体长</p>
                            <h3 class="box-num" style="color:cornflowerblue">10寸</h3>
                            <h4 class="box-updown">较平均（8寸）<img src="../static/img/smartCenter/iconup-1.png" height="16" />25%</h4>
                        </div>
                        <div class="box">
                             <p>体重</p>
                            <h3 class="box-num" style="color:darkorchid">5千克</h3>
                            <h4 class="box-updown" style="margin-left: 4rem;">较平均（4千克）<img src="../static/img/smartCenter/iconup-1.png" height="16" />25%</h4>
                        </div>
                        <div class="box">
                             <p>年龄</p>
                            <h3 class="box-num" style="color:aquamarine">1岁</h3>
                            <h4 class="box-updown">较平均（2岁）<img src="../static/img/smartCenter/icondown-1.png" height="16" />50%</h4>
                        </div>
                        <div class="box">
                             <p>健康</p>
                            <h3 class="box-num" style="color:yellow">较差</h3>
                            <h4 class="box-updown">较平均健康状况<img src="../static/img/smartCenter/icondown-0.png" height="16" /></h4>
                        </div> -->
                    </div>
                </div>
            </div>


           <!-- 右边 -->
           <div class="content-right">
                <div class="content-title">
                    <span>智能决策</span>
                </div>
                <!-- 右边上面 -->
                <div class="right-top">
                    <div id="table2" class="_table2"></div>
                </div>

                <!-- 右边下面 -->
                <div class="right-bottom">
                    <span>智能问答</span>
                </div>

                <div class="chat-container">
                    <div class="chat-header">Chat</div>
                    <div class="chat-content" id="chatContent"></div>
                    <div class="chat-input" >
                        <input type="text" id="chatInput" placeholder="Type a message...">
                        <button id="sendButton">Send</button>
                        <button id="suggestButton">Suggest</button>"
                    </div>
                </div>
           </div>

        </div>
    </div>


</body>

<script src="../static/js/dataCenter/echarts.min.js"></script>
<script src="../static/js/dataCenter/jquery.min.js"></script>


<script src="../static/js/dataCenter/echart.js"></script>
<script src="../static/js/dataCenter/fontscroll.js"></script>
<script src="../static/js/dataCenter/china.js"></script>

<!-- table0 -->
<script type="text/javascript">
    var quality_history = {{quality_history |safe}}
    console.log(quality_history)

    // 初始化一个空对象用于存储反转后的数据
    var reversedHistory = {};

    // 遍历quality_history[0]中的每个字典
    quality_history[0].forEach(record => {
        // 遍历每个字典的键值对
        for (let key in record) {
            if (record.hasOwnProperty(key)) {
                // 如果reversedHistory中没有这个键，初始化一个空数组
                if (!reversedHistory[key]) {
                    reversedHistory[key] = [];
                }
                // 将当前值添加到对应的键的数组中
                reversedHistory[key].push(record[key]);
            }
        }
    });

    // 静态的 -> 动态的
    var data_ph = reversedHistory['PH'].slice(-7);;
    var data_temp = reversedHistory['水温'].slice(-7);;
    var data_ox = reversedHistory['溶解氧'].slice(-7);;
    var data_do = reversedHistory['浊度'].slice(-7);;

    // 计算一下各项均值（7天的）
    var _ph = data_ph.reduce((acc, cur) => acc + cur, 0) / data_ph.length;
    var _temp = data_temp.reduce((acc, cur) => acc + cur, 0) / data_temp.length;
    var _ox = data_ox.reduce((acc, cur) => acc + cur, 0) / data_ox.length;
    var _do = data_do.reduce((acc, cur) => acc + cur, 0) / data_do.length;

    console.log(_ph,_temp,_ox,_do)

    /*** 计算综合评分 ***/
    // 计算每个部分的得分（离平均值越近越接近1，否则接近0）
    function calculateScore(data, avg, weight) {
        return data.map(value => {
            var ratio = 1 - Math.abs(value - avg) / avg;
            return Math.max(0, ratio) * weight;
        });
    }

    var scores_ph = calculateScore(data_ph, _ph, 25);
    var scores_temp = calculateScore(data_temp, _temp, 25);
    var scores_ox = calculateScore(data_ox, _ox, 25);
    var scores_do = calculateScore(data_do, _do, 25);

    // 计算每天的综合得分
    var totalScores = [];
    for (var i = 0; i < 7; i++) {
        var totalScore = scores_ph[i] + scores_temp[i] + scores_ox[i] + scores_do[i];
        totalScores.push(Math.round(totalScore));
    }
    console.log(totalScores);

    /*** 警报模块 ***/

    // 检测下当天的情况
    if(data_ph[6]<5)alert("当天PH值过低！水质不健康，请关注！")
    else if(data_ph[6]>10)alert("当天PH值过高！水质不健康，请关注！")
    if(data_temp[6]<18)alert("当天水温过低！水质不健康，请关注！")
    else if(data_temp[6]>25)alert("当天水温过高！水质不健康，请关注！")
    if(data_ox[6]<5)alert("当天溶解氧过低！水质不健康，请关注！")
    else if(data_ox[6]>21)alert("当天溶解氧过高！水质不健康，请关注！")
    if(data_do[6]<1)alert("当天浊度过低！水质不健康，请关注！")
    else if(data_do[6]>30)alert("当天浊度过高！水质不健康，请关注！")

    /*** 下面是图表 ***/
    var myChart1 = echarts.init(document.getElementById('table0'));
    option1 = {
      color:['#f1ff00','#00c1ff', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
        // backgroundColor: 'rgba(1,202,217,.2)',
        grid: {
                                        left:20,
                                        right:20,
                                        top:30,
                                        bottom:30
                                    },
       radar: {
           name: {
                  textStyle: {
                      fontSize: 10,
                      color: 'rgba(255,255,255,.8)'
                  }
              },
              splitLine: {
                  lineStyle: {
                      color: [
                          'rgba(1,202,217,.01)', 'rgba(1,202,217,.01)'
                      ].reverse()
                  }
              },
              splitArea: {
                  show: false
              },
              axisLine: {
                  lineStyle: {
                      color: 'rgba(1,202,217,.7)'
                  }
              },
           indicator: [
              { name: '水温', max: 6500 },
              { name: 'PH', max: 16000},
              { name: '浊度', max: 30000},
              { name: '溶解氧', max: 44000}
           ]
       },
       series: [{
           name: '',
           type: 'radar',
           radius : [5, 100],
           center: ['50%', '50%'],
           data : [
               {
                   value : [4300, 10000, 28000, 19000],
                   name : 'value',
               },
                {
                   value : [5000, 14000,  22000, 41000],
                   name : 'max',
                   
               },{
                    value : [3300, 4000, 2000, 30000],
                    name : 'min',
                    
               }
           ]
       }],
       graphic: { // 添加这部分
            type: 'text',
            left: 'center',
            top: 'center',
            z: 100, // 设置 z 轴层级
            style: {
                text: totalScores[6],// 当天的
                textAlign: 'center',
                fill: '#fff',
                fontSize: 32
            }
        }
    };
    myChart1.setOption(option1);

// <!-- table1 -->
    var myChart2 = echarts.init(document.getElementById('table1'));
    option2 = {
      color:['#7de494','#7fd7b1', '#5578cf', '#5ebbeb', '#d16ad8','#f8e19a',  '#00b7ee', '#81dabe','#5fc5ce'],
        backgroundColor: 'rgba(1,202,217,.2)',

        grid: {
          left:30,
          right:40,
          top:30,
          bottom:20,
            containLabel: true
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: true,
            name: "日期",
            axisLine:{
              lineStyle:{
                color:'rgba(255,255,255,.2)'
              }
            },
            splitLine:{
              lineStyle:{
                color:'rgba(255,255,255,.1)'
              }
            },
            axisLabel:{
                color:"rgba(255,255,255,.7)"
            },
            data: ['6-08','6-09','6-10','6-11','6-12','6-13','6-14']
        },
        yAxis: {
            type: 'value',
            name: "环境得分",
            axisLine:{
              lineStyle:{
                color:'rgba(255,255,255,.2)'
              }
            },
            splitLine:{
              lineStyle:{
                color:'rgba(255,255,255,.1)'
              }
            },
            axisLabel:{
                color:"rgba(255,255,255,.7)"
            },
        },
        series: [
            {
                name:'2014年',
                type:'line',
                stack: '总量',
                //   areaStyle: {normal: {}},// 面积
                // data:[76, 89, 83, 91, 88, 80, 84],
                data: totalScores,// 换成动态的
                label: {
                    show: true, // 开启标签
                    position: 'top' // 标签位置
                },
                markLine: { // 涨跌线
                    data: [
                        {type: 'average', name: '平均值'}
                    ],
                    lineStyle: { // 修改线条颜色
                        color: '#FFFF00' // 黄色
                    },
                    symbol: 'none'// 去掉箭头
                }
            }

        ]
        };
    myChart2.setOption(option2);


// <!-- table2 -->
    var myChart3= echarts.init(document.getElementById('table2'));
    option3 = {
      color:['#76c4bf','#e5ffc7','#508097','#4d72d9'],
        backgroundColor: 'transparent',// 透明
        grid: {
                            left:10,
                            right:40,
                            top:0,
                            bottom:0,
        containLabel: true
                        },
        calculable : true,
        series : [

            {
                name:'面积模式',
                type:'pie',
                radius : [10, 70],
                center : ['50%', '50%'],
                roseType : 'area',
                data:[
                    {value:data_temp[6], name:'温度'},
                    {value:data_ph[6], name:'PH'},
                    {value:data_ox[6], name:'溶解氧'},
                    {value:data_do[6], name:'浊度'},

                ],
                label: {
                show: true, // 显示标签
                formatter: '{b}: {c}', // 标签的格式，其中 {b} 代表数据名，{c} 代表数据值
            },
        }
        ]
    };
    myChart3.setOption(option3);

// <!-- AI message -->
// <script type="text/javascript">
    const chatContent = document.getElementById('chatContent');
    const chatInput = document.getElementById('chatInput');
    const sendButton = document.getElementById('sendButton');
    const suggestButton = document.getElementById('suggestButton');
    // print("ss")

    // 显示用户发送的消息
    function addMessage(message, isUser = true) {
        // print('User: ' + message)
        const messageElement = document.createElement('div');
        messageElement.textContent = message;
        messageElement.style.textAlign = isUser ? 'right' : 'left';
        // messageElement.style.margin = '5px 0';
        messageElement.style.font = '#000000';
        messageElement.style.fontSize = '14px';
        // messageElement.style.border = '1px solid rgba(27, 146, 253, 0.5)';
        chatContent.appendChild(messageElement);
        chatContent.scrollTop = chatContent.scrollHeight;
    }
    
    // Function to send a message to the backend
    async function sendMessage(message,ifSuggest = false) {
        if(!ifSuggest)
            addMessage(message);
        chatInput.value = '';

        // Replace with your actual backend URL
        const response = await fetch('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ message })
        });
        const data = await response.json();
        addMessage(data.reply, false);
    }

    sendButton.addEventListener('click', () => {
        // print("me:",message)
        const message = chatInput.value.trim();
        console.log(message)
        if (message) {
            sendMessage(message);
        }
    });

    chatInput.addEventListener('keypress', (event) => {
        if (event.key === 'Enter') {
            console.log("here")
            // print("here")
            const message = chatInput.value.trim();
            if (message) {
                sendMessage(message);
            }
        }
    });

    // 询问环境意见
    suggestButton.addEventListener('click', () => {
        var q = "对渔场环境的决策建议？"
        addMessage(q);
        // // 在这里直接回复就可以
        // // ph决策
        // if(data_ph[6]>_ph){
        //     ph_reply = "（1）ph值"+data_ph[6]+"高于平均值"+_ph.toFixed(2)+"，建议降低ph。"
        // }else{
        //     ph_reply = "1. ph值"+data_ph[6]+"低于平均值"+_ph.toFixed(2)+"，建议提高ph。"
        // }

        // // temp决策
        // if(data_temp[6]>_temp){
        //     temp_reply = "（2）温度值"+data_temp[6]+"高于平均值"+_temp.toFixed(1)+"，建议降低温度。"
        // }else{
        //     temp_reply = "（2） 温度值"+data_temp[6]+"低于平均值"+_temp.toFixed(1)+"，建议提高温度。"
        // }

        // if(data_ox[6]>_ox){
        //     ox_reply = "（3） 溶解氧"+data_ox[6]+"高于平均值"+_ox.toFixed(1)+"，建议降低。"
        // }else{
        //     ox_reply = "（3） 溶解氧"+data_ox[6]+"低于平均值"+_ox.toFixed(1)+"，建议提高。"
        // }

        // if(data_do[6]>_do){
        //     do_reply = "（4） 浊度值"+data_do[6]+"高于平均值"+_do.toFixed(1)+"，建议降低。"
        // }else{
        //     do_reply = "（4）浊度值"+data_do[6]+"低于平均值"+_do.toFixed(1)+"，建议提高。"
        // }

        // reply = ph_reply + "\n" + temp_reply + "\n" + ox_reply + "\n" + do_reply;
        // addMessage(reply, false);

        const message = "我的渔场数据为：当前ph值"+data_ph[6]+"，平均ph值"+_ph.toFixed(2)+"，当前温度值"+data_temp[6]+"，平均温度值"+_temp.toFixed(1)
            +"，当前溶解氧值"+data_ox[6]+"，平均溶解氧值"+_ox.toFixed(1)+"，当前浊度值"+data_do[6]+"，平均浊度值"+_do.toFixed(1)
            +"，请给出我的渔场环境建议。";
            
        console.log(message)
        if (message) {
            sendMessage(message,true);
        }
    });

    


</script>

<!-- 图像识别 -->
<script type="text/javascript">
    const fig = document.getElementById('centerFig');
    const switchButton = document.getElementById('switch');
    const updateButton = document.getElementById('update');
    const uploadButton = document.getElementById('upload');
    const fishId = document.getElementById('fishId');
    const fishName = document.getElementById('fishName');
    const prob = document.getElementById('prob');
    const myfish = document.getElementById('myfish');

    // 鱼类的图像列表
    const imageList = [
        '../static/img/smartCenter/fish/caoyu.jpg',// 0
        '../static/img/smartCenter/fish/hetun1.jpg',// 1
        '../static/img/smartCenter/fish/hetun2.jpg',// 2
        '../static/img/smartCenter/fish/hudieyu.jpg',// 3
        '../static/img/smartCenter/fish/jiyu.jpg',// 4
        '../static/img/smartCenter/fish/jinyu.jpg',// 5
        '../static/img/smartCenter/fish/longyu.jpg',// 6
        '../static/img/smartCenter/fish/luohanyu.jpg',// 7
        '../static/img/smartCenter/fish/nianyu.jpg',// 8
        '../static/img/smartCenter/fish/qingdaofu.jpg',// 9
        '../static/img/smartCenter/fish/shibanyu.jpg',// 10
    ];

    const numDic={
        'ht': 1,
        'hdy': 3,
        'jiny': 5,
        'jy': 4,
        'lhy': 7,
        'ly': 6,
        'ny': 8,
        'qdf': 9,
        'sby': 10
    }

    const fishDic = {
        'ht': "河豚",
        'hdy': "蝴蝶鱼",
        'jiny': "金鱼",
        'jy': "鲫鱼",
        'lhy': "罗汉鱼",
        'ly': "龙鱼",
        'ny': "鲶鱼",
        'qdf': "清道夫",
        'sby': "石斑鱼"
    }

    let currentIndex = 1; // 初始索引
    switchButton.addEventListener('click', () => {
        // 切换到下一个图像
        currentIndex = (currentIndex + 1) % imageList.length;
        fig.src = imageList[currentIndex];
    });

    uploadButton.addEventListener('click', () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*'; // 只允许上传图片文件
        input.style.display = 'none';

        input.onchange = async (e) => {
            const file = e.target.files[0];
            if (file) {
                // const reader = new FileReader();
                // reader.onload = (event) => {
                //     fig.src = event.target.result;
                // };
                // reader.readAsDataURL(file);
                const formData = new FormData();
                formData.append('image', file);
                const response = await fetch('/upload_fig', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                console.log('Upload result:', result);

                if (result.path) {
                    fig.src = result.path; // 使用服务器返回的路径设置图像源
                }
            }
        };

        // 模拟点击文件选择对话框
        input.click();
    });

    /**** 识别模型 ****/
    // 路径传到后端
    async function sendPath(path) {
        const response = await fetch('/recognize', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ path})
        });
        const res = await response.json();
        console.log(res);
        return res;
    }

    // 随机生成ID
    function generateRandomId() {
        const letter = String.fromCharCode(65 + Math.floor(Math.random() * 26)); // 生成随机大写字母
        const numbers = Math.floor(10000 + Math.random() * 90000); // 生成五位随机数字
        return letter + numbers;
    }

    updateButton.addEventListener('click', async() => {
        const path = fig.src;
        console.log(path)
        if (path) {
            const res = await sendPath(path);
            // console.log(res)
            fishId.textContent = generateRandomId();
            fishName.textContent = fishDic[res['class']];
            prob.textContent = res['prob'];
            // myfish.src = path;
            myfish.src = imageList[numDic[res['class']]];// 我们的样本图片
        }
    })


    
</script>

<!-- 体重预测 -->
 <script>
    async function handleClick(){
            
        // 发送 AJAX 请求到后端
        const response = await fetch('/predict_weight', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({test:"test"})
        });

        const data = await response.json();
        console.log(data);
        // 更新 weight 的值
        document.getElementById("Weight").innerText = data.res.toFixed(2)

        var input_data = data.new_values
        document.getElementById("Length1").innerText = input_data['Length1(cm)'][0].toFixed(2)
        document.getElementById("Length2").innerText = input_data['Length2(cm)'][0].toFixed(2)
        document.getElementById("Length3").innerText = input_data['Length3(cm)'][0].toFixed(2)
        document.getElementById("Height").innerText = input_data['Height(cm)'][0].toFixed(2)
        document.getElementById("Width").innerText = input_data['Width(cm)'][0].toFixed(2)


    }
 </script>

</html>